using System;
using System.Collections.Generic;
using System.Xml.Linq;

namespace Lightray.Hattrick.ChppLib.EntityTypes
{
    public class Match : EntityBase
    {
        #region Properties

        public Team HomeTeam { get; protected internal set; }
        public Team AwayTeam { get; protected internal set; }
        public DateTime MatchDate { get; protected set; }
        public MatchType MatchType { get; protected set; }
        public int HomeGoals { get; protected set; }
        public int AwayGoals { get; protected set; }
        public MatchStatus Status { get; protected set; }

        protected internal int HomeTeamId { get; protected set; }
        protected internal int AwayTeamId { get; protected set; }

        #endregion

        protected Match() { }

        public static EntityCollection<Match> FromXml(XDocument matchesXml)
        {
            HattrickXmlReader reader = new HattrickXmlReader(matchesXml);
            DateTime dataTime = reader.ReadDate("FetchedDate");

            List<Match> ret = new List<Match>();
            foreach (var match in  matchesXml.Descendants("Match"))
                ret.Add(Match.FromMatchNode(match, dataTime));

            return ret.ToEntityCollection();
        }

        private static Match FromMatchNode(XElement matchNode, DateTime dataTime)
        {
            HattrickXmlReader reader = new HattrickXmlReader(matchNode);
            return new Match()
            {
                DataTime = dataTime,

                ID = reader.ReadNumber("MatchID"),
                HomeTeamId = reader.ReadNumber("HomeTeamID"),
                AwayTeamId = reader.ReadNumber("AwayTeamID"),
                MatchDate = reader.ReadDate("MatchDate"),
                MatchType = reader.ReadMatchType("MatchType"),
                HomeGoals = reader.ReadNumber("HomeGoals"),
                AwayGoals = reader.ReadNumber("AwayGoals"),
                Status = reader.ReadMatchStatus("Status"),
            };
        }

        public override string ToString()
        {
            return string.Format("{0}@{1}", ID, MatchDate);
        }
    }
}
